#include <stdarg.h>
#include <string.h>

#define Origin_x    (*(unsigned char*)0x90000)
#define Origin_y    (*(unsigned char*)0x90001)
#define Video_base  ((unsigned char*)0xb8000)

extern int vsprintf(char* buf, const char* fmt, va_list args);

static int video_x, video_y;
void init_video(void)
{
    video_x = Origin_x;
    video_y = Origin_y;
}

static void print_char(char c, int x, int y, char color)
{
	unsigned char* video = Video_base;
	video[(y*80+x) * 2] = c;
    video[(y*80+x)*2+1] = color;
}

int print_color(const char* s, char color)
{
    int col = 0;
    for (int i=0; i < strlen(s); i++) {
        if (i != 0 && i % 80 == 0) {
            video_y ++;
            col -= i;
        }
        if (s[i] == '\r')  {
            i++;
            if (s[i+1] == '\n') {
                video_y++;
                col -= i-1;
                continue;
            }
        }
        if (s[i] == '\n') {
            video_y ++;
            col -= i;
            continue;
        }
        print_char(s[i], video_x + col++, video_y, color);
    }
    video_x = (video_x + col) % 80;
}

static char buf[1024];
int printk(const char * fmt, ...)
{
    va_list args;
    int i;
    va_start(args, fmt);
    i = vsprintf(buf, fmt, args);
    va_end(args);

    print_color(buf, 0x07);

    return i;
}

void panic(const char* s)
{
    printk("Kernel panic: %s\n", s);
    for (;;);
}